<?php

declare(strict_types=1);

namespace app\admin\controller;

use think\facade\View; //模板引擎
use app\common\Base;
use think\facade\Request;
use think\exception\ValidateException;
use app\model\Article as ArticleMod;
use app\model\ArticleCat;
use app\validate\ArticleVal;

/**
 * @name 文章管理
 */
class Article extends Base
{

    /**
     * @name 文章列表
     */
    public function list()
    {
        if (request()->isPost()) {
            $param = Request::param();
            $w = '';
            if (isset($param['title']) && $param['title'] != '') {
                $w = "title like '%" . $param['title'] . "%'";
            }
            $list = ArticleMod::list($w, (int)$param['limit'], (int)$param['page']);
            return getBack(0, '', $list['data'], $list['count']);
        }
        return View::fetch();
    }

    /**
     * @name 文章添加
     */
    public function add()
    {
        $cat = ArticleCat::list();
        View::assign('cat', grades($cat));
        if (request()->isPost()) {
            $param = Request::param();
            try { //进入验证
                validate(ArticleVal::class)->check($param);
            } catch (ValidateException $e) {
                return getBack(1, $e->getError());
            }
            unset($param['file']);
            $res = ArticleMod::add($param);
            if ($res) {
                return getBack(0);
            } else {
                return getBack(2);
            }
        }

        return View::fetch();
    }

    /**
     * @name 文章编辑
     */
    public function edit()
    {
        $cat = ArticleCat::list();
        View::assign('cat', grades($cat));
        if (request()->isGet()) {
            $id = Request::param('id');
            $find = ArticleMod::find($id);
            View::assign('find', $find);
        }

        if (request()->isPost()) {
            $param = Request::param();
            try { //进入验证
                validate(ArticleVal::class)->check($param);
            } catch (ValidateException $e) {
                return getBack(1, $e->getError());
            }
            unset($param['file']);
            $res = ArticleMod::edit($param);
            if ($res) {
                return getBack(0);
            } else {
                return getBack(2);
            }
        }
        return View::fetch();
    }

    /**
     * @name 文章删除
     */
    public function del()
    {
        if (request()->isGet()) {
            $id = Request::param('id');
            $res = ArticleMod::del($id);
            if ($res) {
                return getBack(0);
            } else {
                return getBack(2);
            }
        }
    }
}
